/**
 * 
 */
package server.alarmThreads;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import net.sourceforge.prowl.api.DefaultProwlEvent;
import net.sourceforge.prowl.api.ProwlClient;
import net.sourceforge.prowl.api.ProwlEvent;
import net.sourceforge.prowl.exception.ProwlException;
import server.config.ServerConfig;
import server.container.EinsatzAlarm;
import server.container.JProwlInfo;
import server.db.SQL;

/**
 * @author Christian
 * 
 */
public class ProwlThread implements AlarmThread {

	private static Logger logger = Logger.getLogger(ProwlThread.class);

	@Override
	public void alarmiere(final EinsatzAlarm alarm) {

		new Thread(new Runnable() {

			public void run() {

				final StringBuffer builder = new StringBuffer();
				builder.append("-----Prowl alamierung gestartet-----\n");
				List<Thread> threads = new ArrayList<Thread>();
				
				for (final JProwlInfo info : SQL.getProwlAlarmInfos(alarm)) {
					threads.add(new Thread(new Runnable() {

						@Override
						public void run() {

							if (!ServerConfig.getInstance().isDebug()) {
								ProwlClient c = new ProwlClient();
								try {
									int i = 0;
									int wiederholungen = 1;
									if (info.getPrioritaet() >= 2) {
										wiederholungen = 4;
									}
									builder.append(info.getProwlId() + " Priorität:"
											+ info.getPrioritaet());
									builder.append("\n");
									while (i < wiederholungen) {
										String alarmText = alarm.toString();
										if (wiederholungen > 1) {
											alarmText = alarm.toString() + "  " + i;
										}
										ProwlEvent e = new DefaultProwlEvent(info.getProwlId(),
												"Einsatzalarm", alarm.getEinsatzArt(), alarmText,
												info.getPrioritaet());
										builder.append(c.pushEvent(e));
										builder.append("\n");
										// 1 Sekunde warten
										sleep(1000);
										i++;
									}
								} catch (ProwlException e1) {
									builder.append(e1.getMessage());
									builder.append("\n");
									logger.error("Prowl-Fehler", e1);
								} catch (Exception e) {
									builder.append(e.getMessage());
									builder.append("\n");
									logger.error("Prowl-Fehler", e);
								}
							}
						}
					}));
				}
				for (Thread t : threads) {
					t.start();
				}
				for (Thread t : threads) {
					try {
						t.join();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				builder.append("-----Nachricht ueber Prowl gesendet------");
				logger.info(builder.toString());

			}
		}).start();
	}

	/**
	 * 
	 * @param sleep
	 *            Sleep
	 */
	private static void sleep(long sleep) {

		try {
			Thread.sleep(sleep);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
